package jodis.conn.impl;

import jodis.conn.inter.IReply;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import static jodis.JoConstants.CRLF;

public class MultiBulkReply implements IReply {

    private String[] args;

    public static MultiBulkReply makeMultiBulkReply(String[] args) {
        return new MultiBulkReply(args);
    }

    public static MultiBulkReply makeMultiBulkReply(byte[][] args) {
        String[] ss = new String[args.length];
        for (int i=0;i<args.length;i++) {
            ss[i] = new String(args[i]).trim();
        }
        return new MultiBulkReply(ss);
    }
    public MultiBulkReply(String[] args) {
        this.args = args;
    }

    public MultiBulkReply(byte[][] cmdLine) {
        this.args = new String[cmdLine.length];
        for (int i=0;i<cmdLine.length;i++) {
            this.args[i] = new String(cmdLine[i]);
        }
    }

    public String[] getArgs() {
        return args;
    }

    @Override
    public byte[] toBytes() {
        StringBuilder sb = new StringBuilder("*");
        sb.append(this.args.length).append(CRLF);
//        sb.append(String.format("*%d%s", this.args.length, CRLF));
        for (int i=0;i<args.length;i++) {
            if (args[i] == null) {
                sb.append("$-1\r\n");
            } else {
                sb.append("$").append(args[i].length()).append(CRLF).append(args[i]).append(CRLF);
//                sb.append(String.format("$%d%s%s%s", args[i].length(), CRLF, args[i], CRLF));
            }

        }
        return sb.toString().getBytes(StandardCharsets.UTF_8);
    }
}
